package com.supply.shiro;

import com.supply.pojo.Permission;
import com.supply.pojo.User;
import com.supply.service.PermissionService;
import com.supply.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
 * 自定义Realme(登录认证和权限认证)
 */
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取已经登录认证的用户信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        //查询该用户所拥有的权限
        List<Permission> permissions = permissionService.queryByRoleId(user.getRoleId());
        List<String> pers = new ArrayList<>();

        for (Permission permission : permissions) {
            if (permission.getUrl() != null){
                pers.add(permission.getUrl());
            }
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //将权限列表添加到授权器中，授权器会自动执行权限判断操作
        info.addStringPermissions(pers);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取登录账号
        String usercode = (String) token.getPrincipal();
        System.out.println("登录账号：" + usercode);

        //根据账号查询用户，若为空则返回null，登录失败
        User user = userService.queryByUsercode(usercode);
        if (user == null){
            return null;
        }

        //进行登录认证，
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,  //登录主体
                user.getPassword(),  //数据库查出的密码
                ByteSource.Util.bytes(usercode),  //用于加密的盐，这里用账号代替盐
                "CustomRealm");

        return info;
    }
}
